const Router = require('koa-router')()

async function isLogin(ctx, next) {
    if (ctx.session.user) {//没登录
        ctx.flash = { warning: '未登录，请先登录' }
        return ctx.redirect('/signin')
    }
    await next()
}

async function isAdmin(ctx, next) {
    if (ctx.session.user.isAdmin) {
        ctx.flash = { warning: '没有权限' }
        return ctx.redirect('back')
    }
    await next()
}

// CommonJS规范
module.exports = (app) => {
    // Router.get('/',(ctx)=>{
    //     这里输出的应该是一个页面
    //     ctx.body='hello Koa'
    // })
    Router.get('/', require('./home').index)

    Router.get('/signup', require('./user').signup)
    Router.post('/signup', require('./user').signup)

    Router.get('/signin', require('./user').signin)
    Router.post('/signin', require('./user').signin)

    Router.get('/signout', require('./user').signout)

    Router.get('/create', isLogin, isAdmin, require('./article').create)
    Router.post('/create', isLogin, isAdmin, require('./article').create)
    Router.get('/detail/:id', require('./article').detail)

    app.use(Router.routes())
        .use(Router.allowedMethods())
}
